package com.eqdd.yiqidian.ui.discover.workcircle;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.WorkCircleCommentActivityCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CommentResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.mine.UserCardActivity;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.CustomLinkMovementMethod;
import com.eqdd.yiqidian.widget.InputDialogFragment;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.mvc.MVCSwipeRefreshHelper;

import org.reactivestreams.Publisher;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.rong.imkit.utils.RongDateUtils;

public class WorkCircleCommentActivity extends BaseActivity {
    private WorkCircleCommentActivityCustom dataBinding;
    private String workCircleId;
    private MVCSwipeRefreshHelper<List<CommentResultBean>> mvcHelper;
    private SlimAdapterEx slimAdapterExComment;
    private ModelRx2DataSource<CommentResultBean> dataSource;
    private int parentId = 0;
    private InputDialogFragment inputDialogFragment;
    private String staffName;
    private String guid;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_work_circle_comment);
        initTopTitleBar(View.VISIBLE, "所有评论");
    }

    @Override
    public void initData() {
        initInputDialog();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        workCircleId = getIntent().getStringExtra("workCircleId");
        staffName = getIntent().getStringExtra("staffName");
        guid = getIntent().getStringExtra(Config.GUID);
        if (guid.equals(user.getGuid())){
            dataBinding.llCheatMsg.setVisibility(View.GONE);
        }
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        if (slimAdapterExComment == null) {
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            slimAdapterExComment = SlimAdapterEx.create().register(R.layout.list_item_36, new SlimInjector<CommentResultBean>() {
                @Override
                public void onInject(CommentResultBean dataComment, IViewInjector injector) {
                    try {
                        injector.with(R.id.iv_comment_head, v -> ImageUtil.setCircleImage(dataComment.getIphoto(), (ImageView) v))
                                .text(R.id.tv_comment_up_left, dataComment.getStaffName())
                                .text(R.id.tv_comment_down_left, RongDateUtils.getConversationListFormatDate(sf.parse(dataComment.getCreateTime()).getTime(), WorkCircleCommentActivity.this))
                                .text(R.id.tv_comment_down_right, dataComment.getDepartName() + " " + dataComment.getPostName())
                                .text(R.id.tv_comment, dataComment.getMessage())
                                .clicked(R.id.iv_comment_comment, v -> {
                                    parentId = dataComment.getId();
                                    openInput(dataComment.getStaffName(),"0");
                                });
                        ArrayList<CommentResultBean> commentResultBeen = new ArrayList<>();
                        getListComment(dataComment, commentResultBeen);
                        SlimAdapterEx slimAdapterExCommentComment = (SlimAdapterEx) ((RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment)).getAdapter();
                        if (slimAdapterExCommentComment == null) {
                            ((RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment)).setLayoutManager(new LinearLayoutManager(WorkCircleCommentActivity.this));
                            slimAdapterExCommentComment = SlimAdapterEx.create().register(R.layout.list_item_37, new SlimInjector<CommentResultBean>() {
                                @Override
                                public void onInject(CommentResultBean data, IViewInjector injector) {
                                    int start1 = 0;
                                    int end1 = data.getStaffName().length();
                                    int start2 = end1 + 4;
                                    int end2 = start2 + data.getBeforeName().length();
                                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
                                    ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary));
                                    SpannableString spannableString = new SpannableString(data.getStaffName() + " 回复 " + data.getBeforeName() + "说：" + data.getMessage());
                                    spannableString.setSpan(foregroundColorSpan, start1, end1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                    spannableString.setSpan(foregroundColorSpan1, start2, end2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                    ClickableSpan clickableSpan = new ClickableSpan() {
                                        @Override
                                        public void onClick(View widget) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString(Config.GUID, data.getCreater());
                                            startActivity(UserCardActivity.class, bundle);
                                        }
                                    };
                                    ClickableSpan clickableSpan1 = new ClickableSpan() {
                                        @Override
                                        public void onClick(View widget) {
                                            System.out.println("123");
                                        }
                                    };
                                    spannableString.setSpan(clickableSpan, start1, end1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                    spannableString.setSpan(clickableSpan1, start2, end2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                                    // 可以点击
                                    ((TextView) injector.findViewById(R.id.tv_comment_comment)).setMovementMethod(CustomLinkMovementMethod.getInstance());
                                    injector.text(R.id.tv_comment_comment, spannableString)
                                            .clicked(R.id.tv_comment_comment, v -> {
                                                parentId = data.getId();
                                                openInput(data.getStaffName(),data.getCreater());
//
                                            });
                                }
                            }).attachTo((RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment));
                        }
//                        ItemClickSupport.addTo((RecyclerView) injector.findViewById(R.id.recyclerViewCommentComment))
//                                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
//                                    @Override
//                                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
//                                        parentId = commentResultBeen.get(position).getId();
//                                        Bundle bundle = new Bundle();
//                                        bundle.putString("hint", "回复" + commentResultBeen.get(position).getStaffName() + ":");
//                                        inputDialogFragment.setArguments(bundle);
//                                        inputDialogFragment.show(getSupportFragmentManager(), "input");
//                                    }
//                                });
                        slimAdapterExCommentComment.updateData(commentResultBeen);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }).attachTo(dataBinding.recyclerView);
        }
        mvcHelper = new MVCSwipeRefreshHelper<>(dataBinding.swipeRefresh);
        dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSourcce(int page, Rx2DataSource.DoneActionRegister register) {
                return OkGo.<HttpResult<List<CommentResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_COMMENT_LIST)
                        .params("workCircleId", workCircleId)
                        .params("id", page == 1 ? 0 : ((CommentResultBean) slimAdapterExComment.getDataItem(slimAdapterExComment.getData().size() - 1)).getId())
                        .converter(new JsonConverter<HttpResult<List<CommentResultBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        })
                        .adapt(new FlowableBody<HttpResult<List<CommentResultBean>>>())
                        .flatMap(new Function<HttpResult<List<CommentResultBean>>, Publisher<List<CommentResultBean>>>() {
                            @Override
                            public Publisher<List<CommentResultBean>> apply(@NonNull HttpResult<List<CommentResultBean>> listHttpResult) throws Exception {
                                return Flowable.just(listHttpResult.getItems() == null ? new ArrayList<CommentResultBean>() : listHttpResult.getItems());
                            }
                        });
            }
        }, 10);
        slimAdapterExComment.updateData(new ArrayList());
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterExComment);
        mvcHelper.refresh();
    }

    @Override
    public void setView() {

    }

    private void initInputDialog() {
        inputDialogFragment = new InputDialogFragment();
        inputDialogFragment.setOnClickListener(s -> {
                    OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.WORK_CIRCLE_COMMENT)
                            .params("companyId", user.getCompanyId())
                            .params("userGuid", user.getGuid())
                            .params("message", s)
                            .params("workCircleId", workCircleId)
                            .params("parentId", parentId)
                            .execute(new DialogCallBack<HttpResult>(this) {
                                @Override
                                public void onSuccess(Response<HttpResult> response) {
                                    HttpResult httpResult = response.body();
                                    ToastUtil.showShort(httpResult.getMsg());
                                    if (httpResult.getStatus() == 200) {
                                        inputDialogFragment.dismiss();
                                        mvcHelper.refresh();
                                    }
                                }
                            });
                }
        );
    }

    public void getListComment(CommentResultBean commentResultBean, List<CommentResultBean> list) {
        if (commentResultBean.getChildren() == null || commentResultBean.getChildren().size() == 0) {
            return;
        } else {
            for (int i = 0; i < commentResultBean.getChildren().size(); i++) {
                list.add(commentResultBean.getChildren().get(i));
                getListComment(commentResultBean.getChildren().get(i), list);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_msg:
                parentId=0;
                openInput(staffName,"0");
//                Bundle bundle = new Bundle();
//                bundle.putString("hint", "回复" + staffName + ":");
//                inputDialogFragment.setArguments(bundle);
//                inputDialogFragment.show(getSupportFragmentManager(), "input");
                break;
        }
    }

    private void openInput(String replyName, String replyGuid) {
        if (user.getGuid().equals(replyGuid)) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("hint", "回复" + replyName + ":");
        inputDialogFragment.setArguments(bundle);
        inputDialogFragment.show(getSupportFragmentManager(), "input");
    }
}
